# Date: Jan 24th, 2021
# Author: geozhang
import json
import time

import pika

from rabbitmq.rabbitmq_rpc import MQ_CONFIG, Consumer01


def consumer_process(num=1):
    """ num: consumer的编号 """
    print(" [C] 第%s个consumer" % str(num))

    # 定义具体的处理方法
    def request_handler(channel, properties, request_body_json: str):
        """ 具体的消息处理方法 """

        """ 处理request """
        # 处理请求request消息体
        request_body = json.loads(request_body_json)
        print(request_body)
        response_body = []
        for request_unit in request_body:
            i_str = str(request_unit["id"])
            print(" [C] 读取 No.{0} picture str: {1}".format(i_str, request_unit["picstr"]))

            # 生成response消息体
            response_unit = {}
            response_unit["id"] = i_str
            response_unit["status"] = "No.%s picture OK" % i_str
            response_body.append(response_unit)

        time.sleep(3)
        """ 产生response，转成json格式 """
        response_body_json = json.dumps(response_body)
        print(" [C] Done, the response body is %s" % response_body_json)

        # 生成response消息头
        response_properties = pika.BasicProperties(correlation_id=properties.correlation_id)

        # 发送response
        channel.exchange_declare(exchange=MQ_CONFIG.get("response_exchange01"), durable=True)
        channel.basic_publish(exchange=MQ_CONFIG.get("response_exchange01"),
                              routing_key=MQ_CONFIG.get("response_routing_key01"),
                              properties=response_properties,
                              body=response_body_json)
        print(" [C] 已经发送response")

    consumer = Consumer01(host=MQ_CONFIG.get("host"),
                          port=MQ_CONFIG.get("port"),
                          virtual_host=MQ_CONFIG.get("virtual_host"),
                          auto_ack=True,
                          durable=True)

    # 开始消费
    consumer.start(MQ_CONFIG.get("request_exchange01"),
                   MQ_CONFIG.get("request_queue01"),
                   MQ_CONFIG.get("request_routing_key01"),
                   request_handler)


#
# def main():
#     for i in range(1):
#         Thread(target=consumer_handler, args=(i + 1,)).start()  # 消费者


if __name__ == '__main__':
    consumer_process()
